package leetcode.offer;

/**
 * ClassName: Offer29
 * Description: leetcode - 剑指offer 29 逆时针打印数组
 * date: 2021-11-22 21:24
 *
 * @author liyifan
 */
public class Offer29 {
    public int[] spiralOrder(int[][] matrix) {
        if (matrix.length == 0 && matrix[0].length == 0)
            return new int[]{};
        int left = 0;
        int up = 0;
        int right = matrix[0].length - 1;
        int down = matrix.length - 1;
        int count = 0;
        int[] res = new int[matrix.length * matrix[0].length];
        while (left <= right && up <= down) {
//            System.out.println("left: " + left + " right: " + right + " up: " + up + " down: " + down);
            // 从左到右
            if (count == res.length)
                break;
            for (int i = left;i <= right;i++) {
//                System.out.println("从左到右");
//                System.out.println("count: " + count + " up: " + up + " i: " + i);
                res[count++] = matrix[up][i];
            }

            // 从上到下
            if (count == res.length)
                break;
            for (int i = up + 1;i <= down;i++) {
                System.out.println("从上到下");
                System.out.println("count: " + count + " right: " + right + " i: " + i);
                res[count++] = matrix[i][right];
            }

            // 从右到左
            if (count == res.length)
                break;
            for (int i = right - 1;i >= left;i--) {
                System.out.println("从右到左");
                System.out.println("count: " + count + " down: " + down + " i: " + i);
                res[count++] = matrix[down][i];
            }

            // 从下到上
            if (count == res.length)
                break;
            for (int i = down - 1;i > up;i--) {
                System.out.println("从下到上");
                System.out.println("count: " + count + " left: " + left + " i: " + i);
                res[count++] = matrix[i][left];
            }
            left++;
            right--;
            up++;
            down--;
        }

        return res;
    }
}
